package com.myapp.myhome.activity;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetDataCallback;
import com.myapp.myhome.R;
import com.myapp.myhome.fragment.Fragment_Home;
import com.myapp.myhome.fragment.Fragment_Setting;
import com.myapp.myhome.fragment.Fragment_User;
import com.myapp.myhome.utils.ACache;
import com.myapp.myhome.utils.AllUtils;
import com.myapp.myhome.utils.MyPreferences;

public class MainActivity extends FragmentActivity {
	private RadioGroup mGroup;
	private Fragment homeFragment;
	private Fragment userFragment;
	private Fragment settingFragment;
	private Fragment mContent;
	private FragmentManager fm;
	MyPreferences shareDate;
	private ACache mCache;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (android.os.Build.VERSION.SDK_INT > 18) {
			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.setFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		shareDate = new MyPreferences(this);
		mCache = ACache.get(this);
		getNamesImgs();
		initFragment();
		initView();

	}

	// 这是初始化fragment 也就是刚进去的时候显示的界面
	private void initFragment() {
		fm = getSupportFragmentManager();
		homeFragment = new Fragment_Home();
		mContent = homeFragment;
		fm.beginTransaction().replace(R.id.view_content, mContent).commit();
	}

	private void initView() {
		mGroup = (RadioGroup) this.findViewById(R.id.view_tab);
		mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int length = group.getChildCount();
				for (int i = 0; i < length; i++) {
					RadioButton rgo = (RadioButton) group.getChildAt(i);
					if (rgo.getId() == checkedId) {
						rgo.setBackgroundColor(getResources().getColor(
								R.color.RadioButton_bg_sel));
					} else {
						rgo.setBackgroundColor(getResources().getColor(
								R.color.RadioButton_bg_no));
					}
				}
				switch (checkedId) {
				case R.id.tab_home:
					if (homeFragment == null) {
						homeFragment = new Fragment_Home();
					}
					changeFragment(mContent, homeFragment);
					break;
				case R.id.tab_user:
					if (userFragment == null) {
						userFragment = new Fragment_User();
					}
					changeFragment(mContent, userFragment);
					break;
				case R.id.tab_setting:
					if (settingFragment == null) {
						settingFragment = new Fragment_Setting();
					}
					changeFragment(mContent, settingFragment);
					break;
				}
			}
		});

	}

	// 切换页卡
	private void changeFragment(Fragment from, Fragment to) {
		if (mContent != to) {

		}
		mContent = to;
		FragmentTransaction ft = fm.beginTransaction();
		if (!to.isAdded()) {
			ft.hide(from).add(R.id.view_content, to).commit();
		} else {
			ft.hide(from).show(to).commit();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			backExit();
			break;
		}

		return true;
	}

	boolean isdown = false;

	private void backExit() {
		Timer timer = new Timer();
		if (!isdown) {
			isdown = true;
			AllUtils.showToast(this, "再次点击退出程序");
			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					isdown = false;
				}
			};
			timer.schedule(task, 2000);
		} else {
			finish();
			// removeCache();
			mCache.remove("testBitmap");
			System.exit(0);
		}
	}

	// 取得名字和头像 将其存储起来----找到了一个缓存框架
	public void getNamesImgs() {
		final String home = "302home";
		final Set<String> siteno = new HashSet<String>();
		AVQuery<AVObject> query = new AVQuery<AVObject>("userTable");
		query.orderByAscending("uid");
		// query.setCachePolicy(AVQuery.CachePolicy.CACHE_ELSE_NETWORK); // 设置缓存
		// query.setMaxCacheAge(TimeUnit.HOURS.toMillis(1));
		query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> arg0, AVException arg1) {
				for (int i = 0; i < arg0.size(); i++) {
					AVObject post = arg0.get(i);
					// 这边也需要取出名字
					final String str = post.getString("uname");
					siteno.add(str);
					// 这边取出头像
					AVFile avFile = post.getAVFile("img");
					if (avFile == null) {
						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), R.drawable.tx_no);
						bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200,
								true);
						mCache.put(str, bitmap, 2 * ACache.TIME_HOUR);
					} else {
						avFile.getDataInBackground(new GetDataCallback() {
							@Override
							public void done(byte[] arg0, AVException arg1) {
								Bitmap bitmap = BitmapFactory.decodeByteArray(
										arg0, 0, arg0.length);
								bitmap = Bitmap.createScaledBitmap(bitmap, 200,
										200, true);
								mCache.put(str, bitmap, 2 * ACache.TIME_HOUR);
							}
						});
					}
				}
				shareDate.setList(home, siteno);
			}
		});
	}

}
